package cn.yr.blog.controller.app;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import cn.yr.blog.service.AccessLogService;
import cn.yr.common.core.domain.entity.YrAccessLog;
import cn.yr.common.core.utils.IpAddressUtil;
import cn.yr.common.core.utils.IpUtil;
import cn.yr.common.exception.ret.Ret;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Api(tags = "app访问记录")
@RequestMapping("/app/accessLog")
@RestController
public class AppAccessLogController {

    @Resource
    private AccessLogService accessLogService;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;


    @ApiOperation(value = "新增访问记录")
    @RequestMapping("add")
    public Ret add(HttpServletRequest request){

        String localIp = "127.0.0.1";
        String ip = IpUtil.getRealIP(request);
        String redisKey = "accessLog:"+ip;
        if(ObjectUtil.isNotEmpty(redisTemplate.opsForValue().get(redisKey))){
            return Ret.success();
        }
        redisTemplate.opsForValue().set(redisKey, ip,2, TimeUnit.HOURS);

        String uaStr = request.getHeader("User-Agent");
        YrAccessLog yrAccessLog = new YrAccessLog();
        UserAgent ua = UserAgentUtil.parse(uaStr);
        yrAccessLog.setBrowser(ua.getBrowser().toString());
        yrAccessLog.setCreateTime(new Date());
        yrAccessLog.setMobile(ua.isMobile()?1:0);
        yrAccessLog.setOs(ua.getOs().toString());
        if(StrUtil.equals(ip,localIp)){
            return Ret.success();
        }
        yrAccessLog.setIp(ip);
        yrAccessLog.setAddress(IpAddressUtil.getAddress(ip));
        accessLogService.save(yrAccessLog);
        return Ret.success();
    }

}
